package com.komon.object.response;

import java.io.IOException;
import java.io.OutputStream;


/**
 * Chunked-Body   = 	*chunk
                        last-chunk
                        trailer
                        CRLF
       chunk          = chunk-size [ chunk-extension ] CRLF
                        chunk-data CRLF
       chunk-size     = 1*HEX
       last-chunk     = 1*("0") [ chunk-extension ] CRLF
       chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
       chunk-ext-name = token
       chunk-ext-val  = token | quoted-string
       chunk-data     = chunk-size(OCTET)
       trailer        = *(entity-header CRLF)

 * @author timon.zhang
 *
 */
public class ChunkedResponseOutputStream extends ResponseOutputStream {
	public ChunkedResponseOutputStream(HttpResponse response,
			OutputStream socketOutputStream) {
		super(response, socketOutputStream);
	}
	
	/* (non-Javadoc)
	 * @see com.komon.object.response.ResponseOutputStream#flush()
	 */
	@Override
	public synchronized void flushBody() throws IOException {
		int lengthOfData = bufferOffset;
		//TODO judge whether use chunked encoding or content-length
		//use chunked encoding
		messageWriter.writeCRLFLine(Integer.toHexString(lengthOfData) + " ");
		messageWriter.flush();
		
		socketOutputStream.write(buffer,0,lengthOfData);
		socketOutputStream.flush();
	}

	/* (non-Javadoc)
	 * @see java.io.OutputStream#close()
	 */
	/**
	 * ouput last chunk
	 */
	@Override
	public void close() throws IOException {
		super.close();
		messageWriter.writeCRLFLine("");
		messageWriter.writeCRLFLine("0" + " ");
		messageWriter.writeCRLFLine("");
		messageWriter.flush();
	}
	
}
